#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <dirent.h>
#include <sys/ioctl.h>  
#include <sys/fcntl.h>
#include <pthread.h>
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "USER_CFG.h"
#include <sys/time.h>
#include <libxml/xmlmemory.h> 
#include <libxml/parser.h> 

#include <linux/watchdog.h>

#define FIFO	"/fifo"
#define SONG_CHNUM 100

#define MAXLINE 80
#define SERV_PORT 8000
#define MEDIA_UPDATE_PORT 9501
#define MPLAYER_PORT 2222

#define DEBUG 1

int berry_mplayer = 0;
int mute_flag = 0;

typedef struct media_play_info{
	
	unsigned char media_play_type[20];
	unsigned char media_play_filename[40];
	time_t media_play_startdate;
	time_t media_play_stopdate;
	time_t media_play_starttime;
	time_t media_play_stoptime;
	int media_play_priority;
	
}MEDIAPLAYINFO; 

MEDIAPLAYINFO meida_info0[1];
MEDIAPLAYINFO meida_info[200];
MEDIAPLAYINFO meida_info_cur[1];
MEDIAPLAYINFO meida_info_next[1];

_enum_DMODE G_DispMode = dmode_0C;
extern unsigned int GUI_LCM_XMAX,GUI_LCM_YMAX;
extern REGION G_REG_DIR;
extern REGION G_REG_FLR;
extern REGION G_REG_TIME;
extern REGION G_REG_DAY;
extern REGION G_REG_WEEK;
extern REGION G_REG_ALARM;
extern REGION G_REG_BKGND;
extern REGION G_REG_LOGO;
extern REGION G_REG_OTHER;
extern REGION G_REG_VIDEO;
extern REGION G_REG_TXT;
unsigned int BKGND_wait;
unsigned int BKGND_effect;

extern unsigned int G_LFTTXT_txt_vfmode;
extern unsigned int G_LFTTXT_vf_speed;
extern unsigned int G_LFTTXT_txt_color;

REGION G_REG_DIR_T2;
REGION G_REG_FLR_T2;
REGION G_REG_ALARM_T2;
REGION REG_DES;
char video_xy[20];
char video_x[10];
char video_y[10];
int media_num = 0;
int fifo_fd; 
pid_t play_pid=9999;
int vol;

char video[100][40];

volatile char next_play_flag = 0;

int local_media_num = 0;
int local_play = 0;
void  send_cmd( char  *cmd) //通过有名管道向mplayer发送命令   
{  
	printf("#####send_cmd %s#####\n",cmd);
	if ((write(fifo_fd,cmd,strlen(cmd)))!=strlen(cmd))  
	{  
		perror("write cmd");  
	}  
}  

int myplay(char* cmd)
{
    
    char volum[20];
    pid_t child, status;
    if ((child = fork()) < 0) {
        perror("fork");
        return 1;
    }
    if(child == 0){
        //execlp("./mplayer" , "mplayer" , "-cache", "1024", "-osdlevel", "0", "-fs" ,  "-geometry", video_xy, "-x" , video_x , "-y" , video_y , "-slave" , "-quiet" , "-input" , "file=/fifo" , cmd, NULL);
        execlp("./mplayer" , "mplayer" , "-cache", "1024", "-osdlevel", "0", "-fs" ,  "-geometry", video_xy, "-slave" , "-quiet" , "-input" , "file=/fifo" , cmd, NULL);
        return -1;
    } else {

	memset(volum,0,20);
	FILE *VOLUME = fopen("/mnt/bootdev/volume.cfg","rb");	
	vol=fgetc(VOLUME);	
	fclose(VOLUME);
	sprintf(volum,"volume %d 1\n",vol);
	sleep(2);
	printf("volume=%d\n",vol);
	while(mute_flag)
		usleep(100000);
	send_cmd(volum);
	mute_flag = 0;

	//play_pid = child;

        if(wait(&status) < 0) {
	    //system("killall mplayer");
            perror("wait");
            return -1;
        }
	//system("killall -9 mplayer");
    }
    return status;
}

int pic_play(char* cmd)
{
    pid_t child, status;
    if ((child = fork()) < 0) {
        //perror("fork");
        return 1;
    }
    if(child == 0){
    
    if( (G_DispMode == dmode_180C) || (G_DispMode == dmode_270C) )
        execlp("./eog" , "eog" , cmd, video_x, video_y, "1", NULL);
    else
    	execlp("./eog" , "eog" , cmd, video_x, video_y, NULL);
        return -1;
    } else {
	play_pid = child;
        if(wait(&status) < 0) {
            perror("wait");
            return -1;
        }
    }
    return status;
	
}

int ffmpage(char* cmd)
{
    pid_t child, status;
    if ((child = fork()) < 0) {
        //perror("fork");
        return 1;
    }
    if(child == 0){
        execlp("./tsplayer" , "tsplayer" , cmd, NULL);
        return -1;
    } else {
	//play_pid = child;		
        if(wait(&status) < 0) {
	    //system("killall tsplayer");
            perror("wait");
            return -1;
        }
	//system("killall -9 tsplayer");
    }
    return status;
}


void  *fifo_write_pthread()	
{  
	struct sockaddr_in servaddr, cliaddr;
	socklen_t cliaddr_len;
	int sockfd;
	char buf[MAXLINE];
	char str[INET_ADDRSTRLEN];

	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(SERV_PORT);
	bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
	//printf("Accepting connections ...\n");
	
	FILE *VOLUME = fopen("/mnt/bootdev/volume.cfg","rb");	
	
	if(VOLUME == NULL)
	{
		VOLUME = fopen("/mnt/bootdev/volume.cfg","wb");
		fputc(20,VOLUME);
		fclose(VOLUME);
		system("sync");
		
		vol=20;
	}
	else
	{
		vol=fgetc(VOLUME);	
		fclose(VOLUME);
	}
	
	while (1)  
	{  
		cliaddr_len = sizeof(cliaddr);
		recvfrom(sockfd, buf, MAXLINE, 0, (struct sockaddr *)&cliaddr, &cliaddr_len);

		switch(buf[0])
		{
			case 'p':
				mute_flag = 1;
				send_cmd("pause\n");
        		break;
			case 'n':
				mute_flag = 0;
				send_cmd("stop\n");
        		break;
			case 'm':
				mute_flag = 0;
				send_cmd("mute 1\n");
				break;
			case 'w':
				mute_flag = 0;
				send_cmd("mute 0\n");
				break; 
			case '*':
				mute_flag = 0;
				//send_cmd("volume 100 1\n");
				send_cmd("volume 1\n");
				vol=vol+3;
				if(vol>=100)
				vol=99;
				printf("vol+=%d\n",vol);
				VOLUME = fopen("/mnt/bootdev/volume.cfg","wb");
				fputc(vol,VOLUME);
				fclose(VOLUME);
				system("sync");
        			break; 
			case '/':
				mute_flag = 0;
				send_cmd("volume -1\n"); 
				vol=vol-3;
				if(vol<3)
				vol=0;
				printf("vol-=%d\n",vol);
				VOLUME = fopen("/mnt/bootdev/volume.cfg","wb");
				fputc(vol,VOLUME);
				fclose(VOLUME);
				system("sync");
				break; 
 			default:
				mute_flag = 0;
				printf("default\n");
				break;

		}
		usleep(1000);
	} 
	return	NULL;  
} 

void  *mplayer_listen_pthread()	
{  
	struct sockaddr_in servaddr, cliaddr;
	socklen_t cliaddr_len;
	int sockfd,n;
	char buf[MAXLINE];
	static int listen_num = 0;
	
	struct timeval outtime;
	outtime.tv_sec = 2;
	outtime.tv_usec = 0;
	sleep(10);
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	setsockopt(sockfd, SOL_SOCKET,SO_RCVTIMEO, &outtime,sizeof(outtime));	
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(MPLAYER_PORT);
	int z = bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
	
	
	printf("\n######################bind_z = %d#########################\n",z);
	
	//listen(sockfd, 4);
	
	int opt = 1;
	setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
	
	printf("mplayer_listen_pthread start ...\n");
	while (1)  
	{   
		//printf("berry_mplayer = %d\n",berry_mplayer);
		if(berry_mplayer == 1)
		{						
			n=0;
			memset(buf,0,MAXLINE);
			cliaddr_len = sizeof(cliaddr);
			n=recvfrom(sockfd, buf, MAXLINE, 0, (struct sockaddr *)&cliaddr, &cliaddr_len);
			printf("recvfrom_n= %d\n",n);
			if(n>0)
			{
				listen_num = 0;
				printf("receive : %s\n",buf);
			}
			else
			{
				printf("\nlisten_num = %d\n",listen_num);
				listen_num++;
	
				if(listen_num>=100)
					//listen_num = 0;
				//if(0)
				{
					printf("can't receive info from mplayer\n");
					listen_num = 0;
					system("killall -2 mplayer");
					usleep(500000);
					system("killall -9 mplayer");
				}
			}
		}
		else
		{
			listen_num = 0;
		}
		usleep(500000);
	}
}

struct tm info_time1;
struct tm *info_time=&info_time1;
int year,mon,day;
int h,min,sec;
int prio;

getReference(xmlNodePtr cur)
{
	char* value=NULL;
	cur=cur->xmlChildrenNode;

	while(cur !=NULL)
	{
		if( (!xmlStrcmp("Weather",(char*)(cur->name)))|| (!xmlStrcmp("WeatherWidth",(char*)(cur->name)))|| (!xmlStrcmp("Software",(char*)(cur->name)))\
		    || (!xmlStrcmp("Text",(char*)(cur->name))) || (!xmlStrcmp("Lift",(char*)(cur->name))))
		{
			cur=cur->next;
			continue;
		}

		if( (!xmlStrcmp("Video",(char*)(cur->name))) || (!xmlStrcmp("Stream",(char*)(cur->name))) )
		{		
			media_num++;
			memset(meida_info[media_num-1].media_play_type,0,20);
			value=(char*)xmlGetProp(cur,"type");			
			sprintf(meida_info[media_num-1].media_play_type,"%s",value);
			xmlFree(value);	
			if(DEBUG)
			printf("\ntype is %s\n",meida_info[media_num-1].media_play_type);	
			
		}

		if( (!xmlStrcmp("FileName",(char*)(cur->name))) )
		{
			memset(meida_info[media_num-1].media_play_filename,0,40);
			value=(char*)xmlNodeGetContent(cur);		
				sprintf(meida_info[media_num-1].media_play_filename,"%s",value);
			xmlFree(value);			
			if(DEBUG)
			printf("FileName is: %s\n",meida_info[media_num-1].media_play_filename);
		}

		if( (!xmlStrcmp("StartDate",(char*)(cur->name))) )
		{

			value=(char*)xmlNodeGetContent(cur);			
			sscanf(value,"%d-%d-%d",&year,&mon,&day);
			info_time->tm_year=(year-1900);
			info_time->tm_mon=mon-1;
			info_time->tm_mday=day;
			info_time->tm_hour=0;
			info_time->tm_min=0;
			info_time->tm_sec=0;
			xmlFree(value);
			meida_info[media_num-1].media_play_startdate=mktime(info_time);
			if(DEBUG)
			printf("StartDate is: %d\n",(int)meida_info[media_num-1].media_play_startdate);
		}

		
		if( (!xmlStrcmp("StopDate",(char*)(cur->name))) )
		{
			value=(char*)xmlNodeGetContent(cur);			
			sscanf(value,"%d-%d-%d",&year,&mon,&day);
			info_time->tm_year=(year-1900);
			info_time->tm_mon=mon-1;
			info_time->tm_mday=day;
			info_time->tm_hour=23;
			info_time->tm_min=59;
			info_time->tm_sec=59;
			xmlFree(value);
			meida_info[media_num-1].media_play_stopdate=mktime(info_time);
			if(DEBUG)
			printf("StopDate is: %d\n",(int)meida_info[media_num-1].media_play_stopdate);
		}

		if( (!xmlStrcmp("StartTime",(char*)(cur->name))) )
		{
			value=(char*)xmlNodeGetContent(cur);			
			sscanf(value,"%d:%d",&h,&min);
			meida_info[media_num-1].media_play_starttime=h*3600+min*60;
			xmlFree(value);
			if(DEBUG)
			printf("StartTime is: %d\n",(int)meida_info[media_num-1].media_play_starttime);

		}

		if( (!xmlStrcmp("StopTime",(char*)(cur->name))) )
		{
			value=(char*)xmlNodeGetContent(cur);			
			sscanf(value,"%d:%d",&h,&min);
			meida_info[media_num-1].media_play_stoptime=h*3600+min*60+59;
			xmlFree(value);
			if(DEBUG)
			printf("StopTime is: %d\n",(int)meida_info[media_num-1].media_play_stoptime);
		}

		if( (!xmlStrcmp("Priority",(char*)(cur->name))) )
		{
			value=(char*)xmlNodeGetContent(cur);			
			sscanf(value,"%d",&prio);
			meida_info[media_num-1].media_play_priority=prio;
			xmlFree(value);
			if(DEBUG)
			printf("Priority is: %d\n",meida_info[media_num-1].media_play_priority);
		}
		
		getReference(cur);
		cur=cur->next; 
	}
}

int get_list()
{
	int i,n,j;
	char client_id[40];
	char addr[100];
	char *s;
	memset(client_id,0,40);

	//FILE *ipid_fd=fopen("/v4asys/mac","r");
	//if(ipid_fd!=NULL)
	//{	     
	//	fgets(client_id,40,ipid_fd);
	//	fclose(ipid_fd);
	//}
	memset(addr,0,100);
	strcpy(addr, "/mnt/sdcard/VIDEO/native.xml");
	//strcat(client_id,".xml");
	//strcat(addr,client_id);
	xmlDocPtr doc=NULL;
	xmlNodePtr cur=NULL;

	xmlKeepBlanksDefault (0);//忽略空白行 
	
	doc=xmlParseFile(addr);//创建Dom树
	if(doc==NULL)
	{
		printf("Loading xml file failed.\n");
		return 1; 
	}
	cur=xmlDocGetRootElement(doc);//获取根节点
	if(cur==NULL)
	{
		printf("empty file\n");
		xmlFreeDoc(doc); 
		return 2; 
	}

	media_num=0;
	getReference(cur);
	xmlFreeDoc(doc);	
	n=media_num;

	if(n > 1)
	for(j=0;j<n;j++)
	{
		for(i=0;i<n-j-1;i++)
		{
			if(meida_info[i].media_play_priority > meida_info[i+1].media_play_priority)
			{
				memset( &meida_info0, 0, sizeof(meida_info0) );
				memcpy( &meida_info0, &meida_info[i], sizeof(meida_info0) );
				memset( &meida_info[i], 0, sizeof(meida_info0) );
				memcpy( &meida_info[i], &meida_info[i+1], sizeof(meida_info0) );
				memset( &meida_info[i+1], 0, sizeof(meida_info0) );
				memcpy( &meida_info[i+1], &meida_info0, sizeof(meida_info0) );
			}
		}
		
	}
	/*
	for(j=0;j<n-1;j++)//去掉文件名重复的
	{
		for(i=j+1;i<n;i++)
		{
			if( strcmp(meida_info[j].media_play_filename , meida_info[i].media_play_filename)==0 )
			{
				meida_info[i].media_play_stopdate=0;
			}
		}		
	}
	*/
	printf("\n\nafter sort: meida_info[0].media_play_priority=%d\nmeida_info[%d].media_play_priority=%d\n\n",meida_info[0].media_play_priority,n-1,meida_info[n-1].media_play_priority);
	return 0;

}

int get_net_status()
{
	   FILE *fp;
	   char buf[100];
	   
	   if ((fp = fopen("/sys/class/net/eth0/carrier", "r")) != NULL)
	   {  
		if(fgets(buf, sizeof(buf), fp) != NULL) 
		{
			if (buf[0] == '1')
			{
				fclose(fp);
				return 1;
			}
			else 
			{
				fclose(fp);
				return 0;
			}
		}  
	    }
	    return 0;

}

void get_video_list()
{
	DIR *dir = NULL;
	struct dirent *ptr = NULL;
	int file,i;
	
	for(file=0;file<100;file++)
	{
		for(i=0;i<40;i++)
		{
			video[file][i] = '\0';
		}
	}

	dir = opendir("/v4asys/LIFT/VIDEO/");
	if(dir==NULL)
	{
		printf("opendir /v4asys/LIFT/VIDEO failed\n");
		return;
	}
	i=0;
	while((ptr=readdir(dir))!=NULL)
	{
		if( (strstr(ptr->d_name, ".avi")!=NULL) || (strstr(ptr->d_name, ".jpg")!=NULL) || (strstr(ptr->d_name, ".bmp")!=NULL)\
			||(strstr(ptr->d_name, ".AVI")!=NULL) || (strstr(ptr->d_name, ".JPG")!=NULL) || (strstr(ptr->d_name, ".BMP")!=NULL) )
		{
			memset(video[i], 0, (strlen(ptr->d_name)+1));
			strcpy(video[i], ptr->d_name);
			printf("video[%d]=%s\n",i,video[i]);
			i++;
			printf("%d: %s\n",i,video[i]);
		}
		if(i>98)
			break;
	}
	local_media_num = i;
	closedir(dir);
}


void  *media_cur_play_pthread()
{
	char dir[100];
	int i=0;

	char buf[100];
	struct sockaddr_in servaddr;
	int sockfd, n;
	char str[INET_ADDRSTRLEN];
	socklen_t servaddr_len;
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	bzero(&servaddr, sizeof(servaddr));
	
	int VIDE_FLAG=0;

	servaddr.sin_family = AF_INET;
	inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr);
	servaddr.sin_port = htons(6666);
	

	while(1)
	{
		if(access("/v4asys/mux.bin", 0) == 0)
			VIDE_FLAG = 1;
		else
			VIDE_FLAG = 0;
		if( (G_REG_VIDEO.x_len==0) || (G_REG_VIDEO.y_len==0) )
		{
			sleep(10);
			continue;		
		}
		
		if( (G_REG_VIDEO.x_len>1024) || (G_REG_VIDEO.y_len>720) )
		{
			sleep(10);
			continue;		
		}
	if( (VIDE_FLAG==0)||(local_play==0) )
	{
		for(i = 0;i<local_media_num;i++)
		{
			if( (local_play!=0)&&(VIDE_FLAG==1) )
				break;
					
			memset(meida_info_cur[0].media_play_filename,0,40);		
			memcpy(meida_info_cur[0].media_play_filename,video[i],40);
			memset(meida_info_cur[0].media_play_type,0,20);
			sprintf(meida_info_cur[0].media_play_type,"videofile");
			
			strcpy(dir, "/v4asys/LIFT/VIDEO/");
			strcat(dir,video[i]);
			
			while(mute_flag)
			usleep(100000);

			if( (strstr(dir, ".jpg")!=NULL) || (strstr(dir, ".JPG")!=NULL) || (strstr(dir, ".bmp")!=NULL) || (strstr(dir, ".BMP")!=NULL ))//如果是jpg文件
			{	
				if(access(dir, 0) == 0)
				{
					pic_play(dir);
					sleep(1);
				}
			}
			else if( (strstr(dir,".avi")!=NULL) || (strstr(dir,".AVI")!=NULL) )//如果是avi文件
			{
				if(access(dir, 0) == 0)
				{
					system("killall -2 mplayer");
					berry_mplayer = 1;
					myplay(dir);
					berry_mplayer = 0;
				}
			}
			sleep(1);
	
		}
	}
	else
		{
				
			while(next_play_flag == 0)
				usleep(1000);
	
			memcpy(&meida_info_cur,&meida_info_next,sizeof(meida_info_cur));
			memset(dir,0,100);
			strcpy(dir, "/mnt/sdcard/VIDEO/");
			strcat(dir,meida_info_cur[0].media_play_filename);
			
			while(mute_flag)
				usleep(100000);

			if(strstr(meida_info_cur[0].media_play_type,"streamfile")!=NULL)//如果是流媒体
			{
				memset(buf,0,100);
				strcpy(buf," ");
				strcat(buf,meida_info_cur[0].media_play_filename);
				strcat(buf,".currentmedia");
				sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&servaddr, sizeof(servaddr));
				ffmpage(meida_info_cur[0].media_play_filename);
				sleep(5);
		
			}		
		
			else if(strstr(dir,".jpg")!=NULL)//如果是jpg文件
			{	
				if(access(dir, 0) == 0)
				{
					memset(buf,0,100);
					strcpy(buf," ");
					strcat(buf,meida_info_cur[0].media_play_filename);
					strcat(buf,".currentmedia");
					sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&servaddr, sizeof(servaddr));
					pic_play(dir);
					sleep(1);
				}
			}
			else if(strstr(dir,".avi")!=NULL)//如果是avi文件
			{
				if(access(dir, 0) == 0)
				{
					memset(buf,0,100);
					strcpy(buf," ");
					strcat(buf,meida_info_cur[0].media_play_filename);
					strcat(buf,".currentmedia");
					sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&servaddr, sizeof(servaddr));
					
					system("killall -2 mplayer");
					berry_mplayer = 1;
					myplay(dir);
					berry_mplayer = 0;
					sleep(1);
				}
			}
		}
		sleep(1);
		
		while(mute_flag)
			usleep(100000);
		
	}
}

int main(int argc, char **argv)	
{
	int media_num_var = 0;
	int i,j;
	time_t cur_time;
	int cur_time_t;
	
	int highest_priority_num0[100];
	int highest_priority_num[100];
	int hpn0,hpn;
	int hpn_var;
	int cur_highest_priority=0;
	
	G_DispMode = GetSysCfg();
	
	if((G_DispMode == dmode_90C) || (G_DispMode == dmode_270C))
	{
		i = G_REG_VIDEO.x_len;
		G_REG_VIDEO.x_len = G_REG_VIDEO.y_len;
		G_REG_VIDEO.y_len = i;
	}
	
	memset(video_xy,0,20);
	memset(video_x,0,10);
	memset(video_y,0,10);
	G_REG_VIDEO.x_len = G_REG_VIDEO.x_len/2*2;
	G_REG_VIDEO.y_len = G_REG_VIDEO.y_len/2*2;
	sprintf(video_xy,"%dx%d+0+0",G_REG_VIDEO.x_len,G_REG_VIDEO.y_len);
	sprintf(video_x,"%d",G_REG_VIDEO.x_len);
	sprintf(video_y,"%d",G_REG_VIDEO.y_len);

	unlink(FIFO);//如果管道存在，先删除    
	if (mkfifo( FIFO , 0x600)==-1) //创建有名管道
	{  
		perror("mkfifo" );	 
	}  
	pthread_t tid_get_cmd;
	pthread_t media_cur_play;
	pthread_t media_mplayer_listen;

	if ((fifo_fd=open(FIFO,O_RDWR))==-1)  
	{  
		perror("open" );  
		return 1;   
	}  
	pthread_create(&tid_get_cmd,NULL,fifo_write_pthread,NULL); 
	pthread_create(&media_cur_play,NULL,media_cur_play_pthread,NULL);
	pthread_create(&media_mplayer_listen,NULL,mplayer_listen_pthread,NULL);
	
	struct sockaddr_in servaddr, cliaddr;
	socklen_t cliaddr_len;
	int sockfd, connfd_temp, tcp_socket_readlen;
	char buf[SONG_CHNUM];
	char buf1[SONG_CHNUM];
	char cmd[100];
	memset(cmd,0,100);
	struct timeval outtime;
	memset(buf,0,SONG_CHNUM);
	outtime.tv_sec = 0;
	outtime.tv_usec = 1000;
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	
	setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &outtime,sizeof(outtime));
	int opt = 1;
	setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
	
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(MEDIA_UPDATE_PORT);
	bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
	listen(sockfd, 2);

	struct sockaddr_in servaddr1;
	int sockfd1;
	socklen_t servaddr_len1;
	sockfd1 = socket(AF_INET, SOCK_DGRAM, 0);
	bzero(&servaddr1, sizeof(servaddr1));
	servaddr1.sin_family = AF_INET;
	inet_pton(AF_INET, "127.0.0.1", &servaddr1.sin_addr);
	servaddr1.sin_port = htons(6666);
	int send_num=3;
	
	get_video_list();
	get_list();
	
	meida_info_cur[0].media_play_priority=5;
	

	while(1)
	{
		if(access("/v4asys/mux.bin", 0) != 0)
		{
			sleep(1);
			continue;
		}
		
		if(local_play==0)
		{
			if( access("/mnt/sdcard/VIDEO/native.xml",0)==0 )
			get_list();
		}
		
			
		tcp_socket_readlen=0;
		cliaddr_len = sizeof(cliaddr);
		tcp_socket_readlen=recvfrom(sockfd, buf, SONG_CHNUM, 0, (struct sockaddr *)&cliaddr, &cliaddr_len);
		if(tcp_socket_readlen>0)
		if(strstr(buf,"media")!=NULL)
		{	
			get_list();
			memset(buf,0,SONG_CHNUM);
		}

		for(media_num_var=0;media_num_var<media_num;media_num_var++)
		{
			if( strstr(meida_info[media_num_var].media_play_type,"streamfile")!=NULL )
			{
				if(get_net_status()==1)
					meida_info[media_num_var].media_play_priority=1;
				else 
					meida_info[media_num_var].media_play_priority=4;		
			}
		}
		

		time(&cur_time);
		info_time = localtime(&cur_time);
		cur_time_t = info_time->tm_hour*3600 + info_time->tm_min*60 + info_time->tm_sec;

		for(media_num_var=0;media_num_var<media_num;media_num_var++)
		{
			if( (meida_info[media_num_var].media_play_startdate<=cur_time) && (meida_info[media_num_var].media_play_stopdate>=cur_time) )
			if( (meida_info[media_num_var].media_play_starttime<=cur_time_t) && (meida_info[media_num_var].media_play_stoptime>=cur_time_t) )
			{
				cur_highest_priority=meida_info[media_num_var].media_play_priority;
				if(cur_highest_priority==4)
					continue;
				else
					break;		
			}
		}

		for(media_num_var=0,hpn0=0;media_num_var<media_num;media_num_var++)
		{
			if( (meida_info[media_num_var].media_play_startdate<=cur_time) && (meida_info[media_num_var].media_play_stopdate>=cur_time) )
			if( (meida_info[media_num_var].media_play_starttime<=cur_time_t) && (meida_info[media_num_var].media_play_stoptime>=cur_time_t) )
			if( (meida_info[media_num_var].media_play_priority == cur_highest_priority) )
			{
				highest_priority_num0[hpn0]=media_num_var;
				hpn0++;
			}
		}

		for(j=0;j<hpn0-1;j++)//去掉文件名重复的
		{
			for(i=j+1;i<hpn0;i++)
			{
				if( strcmp(meida_info[highest_priority_num0[j]].media_play_filename , meida_info[highest_priority_num0[i]].media_play_filename)==0 )
				{
					meida_info[highest_priority_num0[i]].media_play_stopdate=0;
				}
			}		
		}

		for(j=0,hpn=0;j<hpn0;j++)
		{
			if(meida_info[highest_priority_num0[j]].media_play_stopdate==0)
			{
				continue;
			}

			highest_priority_num[hpn]=highest_priority_num0[j];
			hpn++;
		}

		hpn_var=0;
		while( hpn_var<hpn )
		{
			if( (meida_info[highest_priority_num[hpn_var]].media_play_priority != meida_info_cur[0].media_play_priority) )
			{
				if(strstr(meida_info_cur[0].media_play_type,"streamfile")!=NULL)
				{
					system("killall -2 tsplayer");
					usleep(500000);
					system("killall -9 tsplayer");
				}
	
				else if(strstr(meida_info_cur[0].media_play_filename,".avi")!=NULL)
				{
					system("killall -2 mplayer");
					usleep(500000);
					system("killall -9 mplayer");
				}

				else if(strstr(meida_info_cur[0].media_play_filename,".jpg")!=NULL)
				{
					system("killall -2 eog");
					usleep(500000);
					system("killall -9 eog");
				}
				next_play_flag = 0;
				memcpy(&meida_info_next,&meida_info[highest_priority_num[hpn_var]],sizeof(meida_info_cur));
				next_play_flag = 1;
				break;
			}
			else
			{
				if( strcmp(meida_info[highest_priority_num[hpn_var]].media_play_filename , meida_info_cur[0].media_play_filename)==0 )
				{
					if( (hpn_var+1) == hpn )//正在播放最后一个文件
					{
						next_play_flag = 0;
						memcpy(&meida_info_next,&meida_info[highest_priority_num[0]],sizeof(meida_info_cur));
						next_play_flag = 1;
					}
					else 
					{
						next_play_flag = 0;
						memcpy(&meida_info_next,&meida_info[highest_priority_num[hpn_var+1]],sizeof(meida_info_cur));
						next_play_flag = 1;
					}
					break;
				}
				else
				{
					if( (hpn_var+1) == hpn )//当查找到最后一个列表时，仍未找到当前播放的文件名
					{	
						if(strstr(meida_info_cur[0].media_play_type,"streamfile")!=NULL)
						{
							system("killall -2 tsplayer");
							usleep(500000);
							system("killall -9 tsplayer");
						}
	
						else if(strstr(meida_info_cur[0].media_play_filename,".avi")!=NULL)
						{
							system("killall -2 mplayer");
							usleep(500000);
							system("killall -9 mplayer");
						}

						else if(strstr(meida_info_cur[0].media_play_filename,".jpg")!=NULL)
						{
							system("killall -2 eog");
							usleep(500000);
							system("killall -9 eog");
						}
						next_play_flag = 0;					
						memcpy(&meida_info_next,&meida_info[highest_priority_num[0]],sizeof(meida_info_cur));
						next_play_flag = 1;
					}
				}
			}
			
			hpn_var++;
		}
		local_play = hpn;
		if(send_num>=3)
		{
		memset(buf1,0,100);
		strcpy(buf1," ");
		strcat(buf1,meida_info_cur[0].media_play_filename);
		strcat(buf1,".currentmedia");
		sendto(sockfd1, buf1, strlen(buf1), 0, (struct sockaddr *)&servaddr1, sizeof(servaddr1));
		send_num = 0;
		}
		send_num++;
		sleep(1);
	}
	
	
	
	pthread_join(tid_get_cmd,NULL);
	pthread_join(media_cur_play,NULL);
	pthread_join(media_mplayer_listen,NULL);
	
	return 0;
}

